package com.dhecp.project.storage.service.impl;

import com.alibaba.fastjson.JSON;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.utils.MessageUtils;
import com.dhecp.common.utils.RandomValueUtils;
import com.dhecp.common.utils.StringUtils;
import com.dhecp.framework.util.ShiroUtils;
import com.dhecp.project.business.domain.LogisticsMmodeGrads;
import com.dhecp.project.logstics.mapper.LogsticsMmodeGradsMapper;
import com.dhecp.project.storage.domain.TsChannelcode;
import com.dhecp.project.storage.mapper.TsChannelcodeMapper;
import com.dhecp.project.storage.service.TsChannelcodeService;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.dhecp.core.constant.DataFiltering;
import com.dhecp.project.system.service.SysDictionaryForFieldService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 渠道代码
(TsChannelcode表)服务实现类
 *
 * @author fxz
 * @since 2023-09-08 09:13:08
 */
@Service("tsChannelcodeService")
public class TsChannelcodeServiceImpl implements TsChannelcodeService {
    @Autowired
    private TsChannelcodeMapper tsChannelcodeMapper;
    
    @Autowired
    private SysDictionaryForFieldService dictionaryForFieldService;

    @Autowired
    private LogsticsMmodeGradsMapper logisticsMmodeGradsMapper;

    /**
     * 通过guid查询单条数据
     *
     * @param params 对象
     * @return 实例对象
     */
    @Override
    public TsChannelcode queryFirstRecord(Map<String, Object> params) throws Exception {
        return this.tsChannelcodeMapper.selectFirstRecordByNid(params);
    }

    /**
    * 查询列表数据
    */
    @Override
    public List<TsChannelcode> queryList(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));	//常规查询条件SQL语句
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句
        return this.tsChannelcodeMapper.select(params);
    }


    /**
     * 新增渠道代码
     * @param params
     * @return
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public AjaxResult insertTsChannelcode(Map<String, Object> params) {
        if (StringUtils.isEmpty(params)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("数据提交失败，必填参数有误！");
        }

        TsChannelcode entity = JSON.parseObject(params.get("infoMap").toString(), TsChannelcode.class);

        if (entity.getCode() == null || entity.getCode().length() == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("数据提交失败，必填参数有误！");
        }
        int count = tsChannelcodeMapper.countByCode(entity);
        if (count != 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("渠道代码重复,请核实再操作！");
        }

        if (entity.getGuid() == null || "".equals(entity.getGuid())){
            entity.setGuid(RandomValueUtils.getGUID());
        }

        entity.setCreatetime(new Date());

        //判断梯度列表是否正确
        List<LogisticsMmodeGrads> grads = JSON.parseArray(params.get("grads").toString(), LogisticsMmodeGrads.class);
        List<LogisticsMmodeGrads> gradsList;
        List<LogisticsMmodeGrads> gradsList1;
        for (LogisticsMmodeGrads logisticsMmodeGrads : grads){
            if (logisticsMmodeGrads.getStartSection().compareTo(logisticsMmodeGrads.getEndSection()) >= 0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("开始值不允许小于等于结束值");
            }
            gradsList = grads.stream().filter(logisticsMmodeGrads1 -> logisticsMmodeGrads.getStartSection().compareTo(logisticsMmodeGrads1.getStartSection()) >= 0
                    && logisticsMmodeGrads.getStartSection().compareTo(logisticsMmodeGrads1.getEndSection()) <= 0
                    && !logisticsMmodeGrads.getGuid().equals(logisticsMmodeGrads1.getGuid())
            ).collect(Collectors.toList());
            gradsList1 = grads.stream().filter(logisticsMmodeGrads1 -> logisticsMmodeGrads.getEndSection().compareTo(logisticsMmodeGrads1.getStartSection()) >= 0
                    && logisticsMmodeGrads.getEndSection().compareTo(logisticsMmodeGrads1.getEndSection()) <= 0
                    && !logisticsMmodeGrads.getGuid().equals(logisticsMmodeGrads1.getGuid())
            ).collect(Collectors.toList());
            if (gradsList.size() != 0 || gradsList1.size() != 0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("区间有重叠");
            }
        }

        List<LogisticsMmodeGrads> logisticsMmodeGradsList = new ArrayList<>();
        for (LogisticsMmodeGrads logisticsMmodeGrads : grads){
            logisticsMmodeGrads.setGuid(RandomValueUtils.getGUID());
            logisticsMmodeGrads.setLogisticsMmodeGuid(entity.getGuid());
            logisticsMmodeGrads.setType("QDDMJZ");
            logisticsMmodeGradsList.add(logisticsMmodeGrads);
        }

        tsChannelcodeMapper.insert(entity);

        logisticsMmodeGradsMapper.insertLogisticsMmodeGradsBatch(logisticsMmodeGradsList);
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"),entity.getGuid());
    }


    /**
     * 修改渠道代码
     * @author fxz
     * @date: 2023-09-22
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public AjaxResult updateTsChannelcode(Map<String, Object> params) {
        if (StringUtils.isEmpty(params)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("数据提交失败，必填参数有误！");
        }

        TsChannelcode entity = JSON.parseObject(params.get("infoMap").toString(), TsChannelcode.class);

        if (entity.getCode() == null || entity.getCode().length() == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("数据提交失败，必填参数有误！");
        }

        int count = tsChannelcodeMapper.countByCode(entity);
        if (count != 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("渠道代码重复,请核实再操作！");
        }
        entity.setUpdatetime(new Date());

        //判断梯度列表是否正确
        List<LogisticsMmodeGrads> grads = JSON.parseArray(params.get("grads").toString(), LogisticsMmodeGrads.class);
        List<LogisticsMmodeGrads> gradsList;
        List<LogisticsMmodeGrads> gradsList1;
        for (LogisticsMmodeGrads logisticsMmodeGrads : grads){
            if (logisticsMmodeGrads.getStartSection().compareTo(logisticsMmodeGrads.getEndSection()) >= 0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("开始值不允许小于等于结束值");
            }
            gradsList = grads.stream().filter(logisticsMmodeGrads1 -> logisticsMmodeGrads.getStartSection().compareTo(logisticsMmodeGrads1.getStartSection()) >= 0
                    && logisticsMmodeGrads.getStartSection().compareTo(logisticsMmodeGrads1.getEndSection()) <= 0
                    && !logisticsMmodeGrads.getGuid().equals(logisticsMmodeGrads1.getGuid())
            ).collect(Collectors.toList());
            gradsList1 = grads.stream().filter(logisticsMmodeGrads1 -> logisticsMmodeGrads.getEndSection().compareTo(logisticsMmodeGrads1.getStartSection()) >= 0
                    && logisticsMmodeGrads.getEndSection().compareTo(logisticsMmodeGrads1.getEndSection()) <= 0
                    && !logisticsMmodeGrads.getGuid().equals(logisticsMmodeGrads1.getGuid())
            ).collect(Collectors.toList());
            if (gradsList.size() != 0 || gradsList1.size() != 0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("区间有重叠");
            }
        }

        //删除物流方式梯度和计重明细列表
        LogisticsMmodeGrads logisticsMmodeGrads2 = new LogisticsMmodeGrads();
        logisticsMmodeGrads2.setLogisticsMmodeGuid(entity.getGuid());


        List<LogisticsMmodeGrads> logisticsMmodeGradsList = new ArrayList<>();
        for (LogisticsMmodeGrads logisticsMmodeGrads : grads){
            logisticsMmodeGrads.setGuid(RandomValueUtils.getGUID());
            logisticsMmodeGrads.setLogisticsMmodeGuid(entity.getGuid());
            logisticsMmodeGrads.setType("QDDMJZ");
            logisticsMmodeGradsList.add(logisticsMmodeGrads);
        }

        tsChannelcodeMapper.update(entity);

        logisticsMmodeGradsMapper.deleteByLogisticsMmodeGuid(logisticsMmodeGrads2);

        logisticsMmodeGradsMapper.insertLogisticsMmodeGradsBatch(logisticsMmodeGradsList);

        return AjaxResult.success(MessageUtils.message("module.success.issuccess"),entity.getGuid());

    }
}

